﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;
using System.Web;
using Joyintech.Model.inpiao365;

namespace Joyintech.Admin.inpiao365
{
    public class FileOperate : System.Web.UI.Page
    {
        private bool _Access;
        private int _FileNum;
        private int _FolderNum;
        private string _FolderPath;
        private string _Value;

        public FileOperate()
        {
            this._FolderNum = 0;
            this._FileNum = 0;
            HttpRequest Request = HttpContext.Current.Request;
            this._FolderPath = Request.QueryString["path"];
        }

        public FileOperate(string fullname)
        {
            this._FolderNum = 0;
            this._FileNum = 0;
            this._FolderPath = fullname;
        }

        private bool CheckExtEdit(string p_ext)
        {
            string allowExt = ".ini|.txt|.log|.asp|.asa|.inc|.ascx|.config|.c|.cpp|.cs|.css|.java|.jsp|.js|.php|.sql|.vb|.xml|.htm|.html|.aspx|";
            return (allowExt.IndexOf(p_ext + "|") != -1);
        }

        private bool CheckExtHighlighter(string p_ext)
        {
            string allowExt = ".c|.cpp|.cs|.css|.java|.jsp|.js|.php|.sql|.vb|.xml|.htm|.html|.aspx|";
            return (allowExt.IndexOf(p_ext + "|") != -1);
        }

        public void CompressFile(string path, string rarName)
        {
            try
            {
                RegistryKey the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
                string the_rar = the_Reg.GetValue("").ToString();
                the_Reg.Close();
                the_rar = the_rar.Substring(1, the_rar.Length - 7);
                string the_Info = " a -ep1 \"" + rarName + "\"  " + path + " -r";
                ProcessStartInfo the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                Process the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void CopyDirectory(string src, string dest)
        {
            DirectoryInfo di = new DirectoryInfo(src);
            foreach (FileSystemInfo fsi in di.GetFileSystemInfos())
            {
                string destName = Path.Combine(dest, fsi.Name);
                if (fsi is FileInfo)
                {
                    File.Copy(fsi.FullName, destName);
                }
                else
                {
                    Directory.CreateDirectory(destName);
                    this.CopyDirectory(fsi.FullName, destName);
                }
            }
        }

        public void CopyFiles(string OldName, string NewName, string type)
        {
            Exception e;
            if (type == "0")
            {
                try
                {
                    this.CopyDirectory(OldName, NewName);
                }
                catch (Exception exception1)
                {
                    e = exception1;
                    base.Response.Write("<script language=javascript>alert('" + e.Message.ToString() + "');</script>");
                }
            }
            else if ((type == "1") && !File.Exists(NewName))
            {
                try
                {
                    File.Copy(OldName, NewName);
                }
                catch (Exception exception2)
                {
                    e = exception2;
                    base.Response.Write("<script language=javascript>alert('" + e.Message.ToString() + "');</script>");
                }
            }
        }

        public void CreateFolder()
        {
            HttpRequest Request = HttpContext.Current.Request;
            if ((this._FolderPath == null) || (this._FolderPath == ""))
            {
                this._FolderPath = base.Server.MapPath("~/uploadfiles/调度/");
            }
            string folderName = Request.Form["txtFolderName"];
            DirectoryInfo dir = new DirectoryInfo(this._FolderPath + @"\" + folderName);
            if (dir.Exists)
            {
                this._Value = "目录名已存在";
            }
            else
            {
                try
                {
                    dir.Create();
                    this._Value = "创建目录成功, 目录名称为: " + folderName;
                }
                catch
                {
                    this._Value = "创建目录失败, 权限不足";
                }
            }
        }

        public void CreateFolderAdd(string mainfolderName, string folderName)
        {
            HttpRequest Request = HttpContext.Current.Request;
            if (mainfolderName != "")
            {
                this._FolderPath = base.Server.MapPath("~/" + mainfolderName);
            }
            DirectoryInfo dir = new DirectoryInfo(this._FolderPath + @"\" + folderName);
            if (dir.Exists)
            {
                this._Value = "目录名已存在";
            }
            else
            {
                try
                {
                    dir.Create();
                    this._Value = "创建目录成功, 目录名称为: " + folderName;
                }
                catch
                {
                    this._Value = "创建目录失败, 权限不足";
                }
            }
        }

        public void DeleteFileFolder(string delName, string delType)
        {
            HttpRequest Request = HttpContext.Current.Request;
            if (delType == "file")
            {
                if (File.Exists(delName))
                {
                    try
                    {
                        File.SetAttributes(delName, FileAttributes.Normal);
                        File.Delete(delName);
                        this._Value = "删除文件成功, 被删除的文件为: " + Path.GetFileName(delName);
                    }
                    catch
                    {
                        this._Value = "删除文件失败, 权限不足";
                    }
                }
                else
                {
                    this._Value = "要删除的文件不存在";
                }
            }
            else if (delType == "folder")
            {
                if (Directory.Exists(delName))
                {
                    try
                    {
                        Directory.Delete(delName, true);
                        this._Value = "删除目录成功, 被删除的目录为: " + Path.GetFileName(delName);
                    }
                    catch
                    {
                        this._Value = "删除目录失败, 权限不足";
                    }
                }
                else
                {
                    this._Value = "要删除的目录不存在";
                }
            }
        }

        public List<FileFolderInfo> GetDirectories(string p_folderPath)
        {
            HttpServerUtility Server = HttpContext.Current.Server;
            HttpRequest Request = HttpContext.Current.Request;
            string urlString = string.Empty;
            List<FileFolderInfo> files = new List<FileFolderInfo>();
            DirectoryInfo dir = new DirectoryInfo(p_folderPath);
            try
            {
                foreach (FileSystemInfo fsi in dir.GetFileSystemInfos())
                {
                    urlString = string.Empty;
                    if (fsi is DirectoryInfo)
                    {
                        DirectoryInfo di = fsi as DirectoryInfo;
                        urlString = "<a href=\"selectAttachment.aspx?path=" + di.FullName.Replace(Server.MapPath("/"), "") + "\"><img src=\"/theme/directory.gif\" alt=\"文件夹\" align=\"absmiddle\" width=\"100\" border=\"0\" /></a>";
                        FileFolderInfo objFolder = new FileFolderInfo(di.Name, Server.UrlEncode(di.FullName), urlString, "", "", 0L, "folder", di.LastWriteTime);
                        files.Add(objFolder);
                        this._FolderNum++;
                    }
                }
                foreach (FileSystemInfo fsi in dir.GetFileSystemInfos())
                {
                    urlString = string.Empty;
                    if (fsi is FileInfo)
                    {
                        string imageUrl;
                        FileInfo fi = fsi as FileInfo;
                        if ((((fi.Extension.ToLower() == ".jpg") || (fi.Extension.ToLower() == ".jpeg")) || ((fi.Extension.ToLower() == ".gif") || (fi.Extension.ToLower() == ".bmp"))) || (fi.Extension.ToLower() == ".png"))
                        {
                            imageUrl = "/" + fi.FullName.Replace(Server.MapPath("~/"), "").Replace(@"\", "/");
                            urlString = "<a style=\"cursor:hand;\" onclick=\"returnImage('" + imageUrl + "');\" ondblclick=\"returnImage('" + imageUrl + "');\"><img width=\"94\" height=\"100\" src=\"/" + fi.FullName.Replace(Server.MapPath("~/"), "") + "\" border=\"0\"></a>";
                        }
                        else
                        {
                            imageUrl = "/" + fi.FullName.Replace(Server.MapPath("~/"), "").Replace(@"\", "/");
                            urlString = "<a style=\"cursor:hand;\" onclick=\"returnImage('" + imageUrl + "');\" ondblclick=\"returnImage('" + imageUrl + "');\"><img width=\"50\" height=\"50\" src=\"/theme/picture.gif\" border=\"0\"></a>";
                        }
                        FileFolderInfo objFile = new FileFolderInfo(fi.Name, Server.UrlEncode(fi.FullName), urlString, "", fi.Extension, fi.Length, "file", fi.LastWriteTime);
                        files.Add(objFile);
                        this._FileNum++;
                    }
                }
                this._Access = true;
            }
            catch
            {
                this._Access = false;
                return files;
            }
            return files;
        }

        private Encoding GetEncoding(FileStream p_fs, out string p_fileEncode)
        {
            Encoding targetEncoding = Encoding.Default;
            p_fileEncode = "ANSI";
            if ((p_fs != null) && (p_fs.Length >= 1L))
            {
                string byte1 = "";
                string byte2 = "";
                string byte3 = "";
                p_fs.Seek(0L, SeekOrigin.Begin);
                byte1 = Convert.ToByte(p_fs.ReadByte()).ToString("X");
                if (p_fs.Length >= 2L)
                {
                    byte2 = Convert.ToByte(p_fs.ReadByte()).ToString("X");
                }
                if (p_fs.Length >= 3L)
                {
                    byte3 = Convert.ToByte(p_fs.ReadByte()).ToString("X");
                }
                if (((byte1 == "EF") && (byte2 == "BB")) && (byte3 == "BF"))
                {
                    targetEncoding = Encoding.UTF8;
                    p_fileEncode = "UTF-8";
                }
                else if ((byte1 == "FF") && (byte2 == "FE"))
                {
                    targetEncoding = Encoding.Unicode;
                    p_fileEncode = "Unicode";
                }
                else if ((byte1 == "FE") && (byte2 == "FF"))
                {
                    targetEncoding = Encoding.BigEndianUnicode;
                    p_fileEncode = "Unicode big endian";
                }
                p_fs.Seek(0L, SeekOrigin.Begin);
            }
            return targetEncoding;
        }

        public void ReadTextFile(string p_filePath, out string p_fileContent, out string p_fileEncode)
        {
            FileStream fs = new FileStream(p_filePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, this.GetEncoding(fs, out p_fileEncode));
            p_fileContent = sr.ReadToEnd();
            sr.Close();
            fs.Close();
        }

        public void RemoveFiles(string OldName, string NewName, string type)
        {
            Exception e;
            if (type == "0")
            {
                if (!Directory.Exists(NewName))
                {
                    try
                    {
                        Directory.Move(OldName, NewName);
                    }
                    catch (Exception exception1)
                    {
                        e = exception1;
                        base.Response.Write("<script language=javascript>alert('" + e.Message.ToString() + "');</script>");
                    }
                }
            }
            else if ((type == "1") && !File.Exists(NewName))
            {
                try
                {
                    File.Move(OldName, NewName);
                }
                catch (Exception exception2)
                {
                    e = exception2;
                    base.Response.Write("<script language=javascript>alert('" + e.Message.ToString() + "');</script>");
                }
            }
        }

        public void RenameFileFolder(string Name)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpServerUtility Server = HttpContext.Current.Server;
            string newName = Request.Form["txtFolderName"];
            string oldName = Name.ToString();
            if (File.Exists(oldName))
            {
                try
                {
                    if (File.Exists(Path.GetDirectoryName(oldName) + @"\" + newName))
                    {
                        this._Value = "文件已存在时, 无法重命名或移动该文件 ";
                    }
                    else
                    {
                        File.Move(oldName, Path.GetDirectoryName(oldName) + @"\" + newName);
                        this._Value = "重命名或移动文件成功, 新的文件名为: " + newName;
                    }
                }
                catch
                {
                    this._Value = "重命名或移动文件失败, 权限不足";
                }
            }
            else
            {
                try
                {
                    if (Directory.Exists(Path.GetDirectoryName(oldName) + @"\" + newName))
                    {
                        this._Value = "目录已存在时, 无法重命名或移动该目录 ";
                    }
                    else
                    {
                        Directory.Move(oldName, Path.GetDirectoryName(oldName) + @"\" + newName);
                        this._Value = "重命名或移动目录成功, 新的目录名为: " + newName;
                    }
                }
                catch (Exception ex)
                {
                    this._Value = ex.Message;
                }
            }
        }

        public void RenameFileFolder1(string Name)
        {
            HttpRequest Request = HttpContext.Current.Request;
            HttpServerUtility Server = HttpContext.Current.Server;
            string newName = Request.Form["txtListName"];
            string oldName = Name.ToString();
            if (File.Exists(oldName))
            {
                try
                {
                    if (File.Exists(Path.GetDirectoryName(oldName) + @"\" + newName))
                    {
                        this._Value = "文件已存在时, 无法重命名或移动该文件 ";
                    }
                    else
                    {
                        File.Move(oldName, Path.GetDirectoryName(oldName) + @"\" + newName);
                        this._Value = "重命名或移动文件成功, 新的文件名为: " + newName;
                    }
                }
                catch
                {
                    this._Value = "重命名或移动文件失败, 权限不足";
                }
            }
            else
            {
                try
                {
                    if (Directory.Exists(Path.GetDirectoryName(oldName) + @"\" + newName))
                    {
                        this._Value = "目录已存在时, 无法重命名或移动该目录 ";
                    }
                    else
                    {
                        Directory.Move(oldName, Path.GetDirectoryName(oldName) + @"\" + newName);
                        this._Value = "重命名或移动目录成功, 新的目录名为: " + newName;
                    }
                }
                catch (Exception ex)
                {
                    this._Value = ex.Message;
                }
            }
        }

        public string SaveTextFile(string p_filePath, string p_fileContent, string p_fileEncode)
        {
            string result;
            Encoding setEncoding = Encoding.Default;
            if (p_fileEncode == "UTF-8")
            {
                setEncoding = Encoding.UTF8;
            }
            else if (p_fileEncode == "Unicode")
            {
                setEncoding = Encoding.Unicode;
            }
            else if (p_fileEncode == "Unicode big endian")
            {
                setEncoding = Encoding.BigEndianUnicode;
            }
            FileStream fs = new FileStream(p_filePath, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, setEncoding);
            try
            {
                sw.Write(p_fileContent);
                sw.Flush();
                result = "<script type=\"text/javascript\">alert(\"保存文件成功\");</script>";
            }
            catch (Exception ex)
            {
                result = "<script type=\"text/javascript\">alert(\"" + ex.Message + "\");</script>";
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
            return result;
        }

        public void unPack(string RarFile, string Folder)
        {
            try
            {
                RegistryKey the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
                string the_rar = the_Reg.GetValue("").ToString();
                the_Reg.Close();
                the_rar = the_rar.Substring(1, the_rar.Length - 7);
                string the_Info = " X  \"" + RarFile + "\" " + Folder;
                ProcessStartInfo the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                Process the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void UploadFile()
        {
            HttpPostedFile fileUpload = HttpContext.Current.Request.Files["fileUpload"];
            if (fileUpload.ContentLength == 0)
            {
                this._Value = "请先选择文件";
            }
            else
            {
                string fileName = Path.GetFileName(fileUpload.FileName);
                if (File.Exists(this._FolderPath + @"\" + fileName))
                {
                    Random rnd = new Random();
                    string newFileName = string.Concat(new object[] { Path.GetFileNameWithoutExtension(fileName), "_", rnd.Next(1, 0x3e8), Path.GetExtension(fileName) });
                    try
                    {
                        fileUpload.SaveAs(this._FolderPath + @"\" + newFileName);
                        this._Value = "上传的文件名已存在, 自动重命名为: " + newFileName;
                    }
                    catch
                    {
                        this._Value = "写入文件失败, 权限不足";
                    }
                }
                else
                {
                    try
                    {
                        fileUpload.SaveAs(this._FolderPath + @"\" + fileName);
                        this._Value = "上传文件完毕, 文件名为: " + fileName;
                    }
                    catch
                    {
                        this._Value = "写入文件失败, 权限不足";
                    }
                }
            }
        }

        public bool Access
        {
            get
            {
                return this._Access;
            }
        }

        public int FileNum
        {
            get
            {
                return this._FileNum;
            }
        }

        public int FolderNum
        {
            get
            {
                return this._FolderNum;
            }
        }

        public string Value
        {
            get
            {
                return this._Value;
            }
        }

        public class FilesComparer : IComparer<FileFolderInfo>
        {
            private string _sortColumn;

            public FilesComparer(string sortExpression)
            {
                this._sortColumn = sortExpression;
            }

            public int Compare(FileFolderInfo a, FileFolderInfo b)
            {
                switch (this._sortColumn.ToLower())
                {
                    case "name":
                        return string.Compare(a.Name, b.Name, StringComparison.InvariantCultureIgnoreCase);

                    case "ext":
                        return string.Compare(a.Ext, b.Ext, StringComparison.InvariantCultureIgnoreCase);

                    case "size":
                        return string.Compare(a.FormatSize, b.FormatSize, StringComparison.InvariantCultureIgnoreCase);

                    case "modifydate":
                        return DateTime.Compare(DateTime.Parse(a.FormatModifyDate), DateTime.Parse(b.FormatModifyDate));
                }
                return string.Compare(a.Name, b.Name, StringComparison.InvariantCultureIgnoreCase);
            }
        }
    }
}